import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const initialState = {
    count: 11
}
// export const asyncIncrement = (payload) => (dispatch) => {
//     setTimeout(() => {
//         dispatch(increment(payload));
//     }, 1000);
// };

// export const asyncIncrement = createAsyncThunk('counter/asyncIncrement',(step)=>{
//     return step
// })
function getData(type){
    return new Promise(function(resolve,reject){
        if(type === 'sucess'){
            resolve('sucess')
        }else if(type === 'fail'){
            reject('fail')
        }
    });
}

export const asyncIncrement = createAsyncThunk('counter/asyncIncrement',async ({type})=>{
    try {
        const res = await getData(type)
        return res
    } catch (error) {
        return '请求失败'
    }
})

const countSlice = createSlice({
    name: 'counter',
    initialState,
    reducers: {
        increment(state,action){
            console.log(action)
            state.count = state.count + action.payload;
        },
        decrement(state,action){
            state.count = state.count - action.payload;
        }
    },
    extraReducers: {
        [asyncIncrement.fulfilled](state,action){
            console.log(action)
            state.count = state.count + action.payload;
        },
        [asyncIncrement.rejected](state,action){
            console.log(action)
        }
    }
})

export const { increment, decrement } = countSlice.actions;
export default countSlice.reducer;